package com.yl.module.user.listener;

import com.yl.exception.MyException;
import com.yl.module.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * @Todo
 * @Author jiangtao
 * @CreateBy 2020-06-16 12:07 AM
 * @UpdateBy jiangtao
 * @Version v1.0
 */
@Slf4j
@Configuration
public class EventListenerConfig {

    @EventListener
    public void handleEvent(Object event) {
        // 监听所有事件， 可以看看系统发布了那些事件
        // 可使用instanceof 监听想监听的事件
        if(event instanceof UserLogEvent) {

        }
        log.info("事件：{}", event);
    }

    @EventListener
    public void handleEvent(UserLogEvent event) {
        // 监听UserLogEvent事件
        log.info("监听到UserLogEvent事件，消息为：{}，发布时间：{}", event.getMsg(), event.getTimestamp());
    }

    @EventListener(condition = "#event.user.genderName == '男'")
    public void handleEvent(UserRegisterEvent event) {
        // 监听UserLogEvent事件
        log.info("监听到genderName等于男的UserRegisterEvent事件，消息为：{}，发布时间：{}", event.getUser(), event.getTimestamp());
    }

    @EventListener
    public void handleEvent(User user) {
        // 类似于 guava 的eventBus
        log.info("监听到对象事件，消息为：{}，发布时间：{}", user);
    }

    // 事物的使用 1. TransactionalEventListener 注解
    @EventListener
    @Transactional(rollbackFor = MyException.class)
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void handleEvent2(UserRegisterEvent userRegisterEvent) {
        User user = userRegisterEvent.getUser();

        // 1.添加到 子表

        // 2. 记录到日志

        // 3. 发送通知
    }

    // 事物的使用 2. TransactionSynchronizationManager方法
    @EventListener
    public void handleEvent3(UserRegisterEvent userRegisterEvent) {
        if(TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(
                    new TransactionSynchronizationAdapter() {
                        @Override
                        public void afterCommit() {
                            //super.afterCommit();
                            User user = userRegisterEvent.getUser();
                        }
                    }
            );
        } else {
            User user = userRegisterEvent.getUser();
        }

        // 1.添加到 子表

        // 2. 记录到日志

        // 3. 发送通知
    }

}
